package com.ywk.effective._9_hashcode;

import java.util.HashMap;

public class PhoneNumber {
    private short areaCode;
    private short prefix;
    private short lineNumber;


    public PhoneNumber(int areaCode, int prefix, int lineNumber) {
        rangCheck(areaCode, 999, " area chode");
        rangCheck(prefix, 999, " prefix");
        rangCheck(lineNumber, 9999, " line number");
        this.areaCode = (short) areaCode;
        this.prefix = (short) prefix;
        this.lineNumber = (short) lineNumber;
    }

    private void rangCheck(int args, int max, String name) {
        if (args < 0 || args > max) {
            throw new IllegalArgumentException(name + ":" + args);
        }
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == this) {
            return true;
        }
        if (!(obj instanceof PhoneNumber)) {
            return false;
        }
        PhoneNumber phoneNumber = (PhoneNumber) obj;
        return phoneNumber.lineNumber == this.lineNumber && phoneNumber.areaCode == this.areaCode &&
                phoneNumber.prefix == this.prefix;
    }
    private volatile int hashCode;
    @Override
    public int hashCode() {
        int result = hashCode;
        result = 31 * result + areaCode;
        result = 31 * result + prefix;
        result = 31 * result + lineNumber;
        return result;
    }

    @Override
    public String toString() {
        return String.format("(%03d) %03d-%04d", areaCode, prefix, lineNumber);
    }

    static class Main{
        public static void main(String[] args) {
            HashMap<PhoneNumber, String> map = new HashMap<>();
            map.put(new PhoneNumber(909, 991, 8907), "Jenny");
            System.out.println((new PhoneNumber(909, 991, 8907)));
            System.out.println(map.get(new PhoneNumber(909, 991, 8907)));

        }
    }
}
